# 权限管理接口
from flask import request, jsonify
from flask_jwt_extended import jwt_required, get_jwt, get_jwt_identity
from backend.models.permission import Permission
from backend.services.permission_admin_service import (
    get_permission_list, create_permission, update_permission, delete_permission, get_permission_by_code
)
from backend.api.user_api import admin_required
from backend.services.unified_log_service import log_service
from backend.models.system_log import SystemLog

@jwt_required()
@admin_required
def list_permissions():
    permissions = get_permission_list()
    return jsonify({'success': True, 'data': permissions})

@jwt_required()
@admin_required
def add_permission():
    data = request.get_json(force=True, silent=True)
    result = create_permission(data)
    
    # 记录系统日志
    if result.get('success'):
        current_user_id = get_jwt_identity()
        ip_address = request.remote_addr
        # 获取当前用户信息
        from backend.models.user import User
        try:
            if current_user_id:
                current_user = User.query.get(int(current_user_id))
                operator = current_user.username if current_user else '未知用户'
            else:
                operator = '系统'
        except (ValueError, TypeError):
            operator = '未知用户'
        
        # 记录系统管理操作日志
        from backend.infrastructure.database import db
        log = SystemLog.log_create(
            record=result.get('data'),
            operator=operator,
            ip_address=ip_address
        )
        if log:
            db.session.add(log)
            db.session.commit()
    
    return jsonify(result)

@jwt_required()
@admin_required
def edit_permission(permission_id):
    data = request.get_json(force=True, silent=True)
    
    print(f"编辑权限请求: permission_id={permission_id}, data={data}")
    
    # 获取修改前的权限数据
    old_permission = get_permission_by_code(permission_id) if ':' in str(permission_id) else Permission.query.get(permission_id)
    old_data = old_permission.to_dict() if old_permission else None
    
    # 直接调用update_permission，它会处理权限不存在的情况
    result = update_permission(permission_id, data)
    print(f"编辑权限结果: {result}")
    
    # 记录系统日志
    if result.get('success'):
        current_user_id = get_jwt_identity()
        ip_address = request.remote_addr
        # 获取当前用户信息
        from backend.models.user import User
        try:
            if current_user_id:
                current_user = User.query.get(int(current_user_id))
                operator = current_user.username if current_user else '未知用户'
            else:
                operator = '系统'
        except (ValueError, TypeError):
            operator = '未知用户'
        
        # 记录系统管理操作日志
        from backend.infrastructure.database import db
        log = SystemLog.log_update(
            record=result.get('data'),
            old_data=old_data,
            operator=operator,
            ip_address=ip_address
        )
        if log:
            db.session.add(log)
            db.session.commit()
    
    return jsonify(result)

@jwt_required()
@admin_required
def remove_permission(permission_id):
    # 获取删除前的权限数据
    old_permission = Permission.query.get(permission_id)
    old_data = old_permission.to_dict() if old_permission else None
    
    result = delete_permission(permission_id)
    
    # 记录系统日志
    if result.get('success'):
        current_user_id = get_jwt_identity()
        ip_address = request.remote_addr
        # 获取当前用户信息
        from backend.models.user import User
        try:
            if current_user_id:
                current_user = User.query.get(int(current_user_id))
                operator = current_user.username if current_user else '未知用户'
            else:
                operator = '系统'
        except (ValueError, TypeError):
            operator = '未知用户'
        
        # 记录系统管理操作日志
        from backend.infrastructure.database import db
        log = SystemLog.log_delete(
            record=old_permission,
            operator=operator,
            ip_address=ip_address
        )
        if log:
            db.session.add(log)
            db.session.commit()
    
    return jsonify(result)
